# -*- mode: python -*-

# ddb imports
from ddb.log import log

# system import
import os

try:
    from pysqlite2 import dbapi2 as sqlite
except:
    import sys
    log.msg('pysqlite2 is not available on this system, database offline'
    sys.exit(1)

class db:
    def __init__(self, name):
        self.connection = sqlite.connect('db/%s.db' % name)
        self.cursor     = self.connection.cursor()
        self.checkDb()

    def checkDb(self):
        if hasattr(self, '_initDb'):
            for table in getattr(self, '_initDb').keys():
                try:
                    self.cursor.execute('SELECT 1 FROM %s WHERE 1 LIMIT1;' %
                        table)
                except Exception, e:
                    self.initTable(table)

    def initDb(self):
        if hasattr(self, '_initDb'):
            for table in getattr(self, '_initDb').keys():
                self.initTable(table)
        else:
            log.msg('Object %s has no _initDb prototype schema!' % self)

    def initTable(self, table):
        statement = getattr(self, '_initDb')[table]
        try:
            self.cursor.execute('BEGIN TRANSACTION')
            self.cursor.execute(statement)
        except Exception, e:
            log.msg('SQL Statement failed: %s' % str(e))
            self.cursor.execute('ROLLBACK TRANSACTION')
            return
        self.cursor.execute('COMMIT TRANSACTION')

